/*
 * @Description: 异步串行钩子
 * @Author: wangqi
 * @Date: 2021-04-18 11:26:38
 * @LastEditTime: 2021-04-18 11:37:19
 */

class AsyncSeriesHook {
    constructor() {
        this.hooks = [];
    }

    tapAsync(name, cb) {
        this.hooks.push(cb);
    }

    callAsync(...res) {
        let index = 0;
        let finalCallback = res.pop();
        let next = () => {
            if (index === this.hooks.length) return finalCallback();
            let hook = this.hooks[index++];
            hook(...res, next);
        };
        next();
    }
}

let asyncserieshook = new AsyncSeriesHook(['name', 'cb']);

asyncserieshook.tapAsync('node', (name, cb) => {
    setTimeout(() => {
        console.log('node', name, cb);
        cb();
    }, 1000);
})

asyncserieshook.tapAsync('vue', (name, cb) => {
    setTimeout(() => {
        console.log('vue', name, cb)
        cb();
    }, 2000);
});

asyncserieshook.callAsync('wq', function () {
    console.log("end")
});






